package cn.wolfcode.rbac.utils;

import cn.wolfcode.rbac.springsecurity.detail.EmployeeDetails;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

public class SecurityUtils {

    /**
     * 返回 SecurityContext 上下文对象
     * @return
     */
    public static SecurityContext getSecurityContext(){
       return SecurityContextHolder.getContext();
    }

    /**
     * 把用户信息存到上下文中
     * @param username  用户名
     * @param password  密码
     */
    public static void setSecurityContextByUsernameAndPassword(String username,String password){
        Authentication usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username,password);
        getSecurityContext().setAuthentication(usernamePasswordAuthenticationToken);
    }

    /**
     * 在上下文中获取用户信息
     * @return EmployeeDetails
     */
    public static EmployeeDetails getUserDetails(){
        return (EmployeeDetails) getSecurityContext().getAuthentication().getPrincipal();
    }
}
